import { fetchEmoticonDelete, fetchEmoticonList } from '@/apis/api'
import { fetchEmoticonCustomizeUpload } from '@/apis/customize'
import { fetchApi, sync } from '@/apis/request'
import { defineStore } from 'pinia'

export const useEditorStore = defineStore('editor', {
  state: () => {
    return {
      // 表包相关
      emoticon: {
        items: [
          {
            name: '系统表情',
            icon: '',
            children: [] as any[]
          },
          {
            name: '我的收藏',
            icon: '',
            children: [] as any[]
          }
        ]
      }
    }
  },
  actions: {
    // 加载用户表情包
    loadUserEmoticon() {
      sync(async () => {
        const { items } = await fetchEmoticonList({})
        this.emoticon.items[1].children = items || []
      })
    },

    // 自定义上传用户表情包
    async uploadUserEmoticon(file: File) {
      const params = new FormData()
      params.append('file', file)

      try {
        const data = await fetchEmoticonCustomizeUpload(params)
        this.emoticon.items[1]?.children?.unshift(data)
      } catch (err) {
        alert(err)
      }
    },

    // 删除自定义上传用户表情包
    async removeUserEmoticon(resoure: { index: number; emoticon_id: number }) {
      const { index, emoticon_id } = resoure

      const [err] = await fetchApi(fetchEmoticonDelete, { emoticon_id })
      if (err) return

      this.emoticon.items[1]?.children.splice(index, 1)
    }
  }
})
